"""
__author__ = '霍格沃兹测试开发学社'
__desc__ = '更多测试开发技术探讨，请访问：https://ceshiren.com/t/topic/15860'
"""
import json

import jsonpath
import requests

from src.utils.log_utils import logger


# todo 适配， 世钧
class BaseApi:

    def __init__(self, base_url, role=None):

        self.base_url = base_url
        # 获取对应的角色信息
        if role:
            self.role = role

    def __set_token(self, request_infos, mobile='15055369706'):
        url = 'https://cmm-cas-test.cds8.cn/v2/cas/authorize'
        jsondata = {
            'mobile': mobile
        }
        data = {
            "grant_type": "code",
            "appId": 18888,
            "mobile": mobile,
            "code": "11",
            "device": "PC"
        }
        res = requests.post(url=url, json=data)
        res_json = res.json()
        str = {'token':jsonpath.jsonpath(res_json, '$..data.token')[0]}

        url_login ='https://ck-medium-api-test.cds8.cn/v1/cas/login'

        res_login = requests.post(url=url_login,json=str)
        res_login_json = res_login.json()
        print()

        str_token=jsonpath.jsonpath(res_login_json,'$..data.token')[0]

        # str_token = f'Bearer {str_token}'
        print()
        self.token = {'Authorization': f'Bearer {str_token}'}

        # # 获取headers， 如果请求本身有头信息，那么就把token信息更新进去
        if request_infos.get("headers"):
            request_infos["headers"].update(self.token)

        else:
            request_infos["headers"] = self.token

        return request_infos

    def send(self, method, path, **kwargs):
        kwargs = self.__set_token(kwargs)
        r = requests.request(method, self.base_url + path, **kwargs)
        logger.debug(f"{path}接口的响应为{json.dumps(r.json(), indent=2, ensure_ascii=False)}")
        return r.json()